package com.tticar.invmanager.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tticar.invmanager.common.utils.MoneyTransformUtil;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.common.utils.date.DateStyle;
import com.tticar.invmanager.common.utils.date.DateUtil;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.*;
import com.tticar.invmanager.mapper.InRepositoryDetailMapper;
import com.tticar.invmanager.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 入库单详情 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-08-02
 */
@Controller
@RequestMapping("/inRepositoryDetail")
public class InRepositoryDetailController extends BaseController {

    @Autowired
    private IInRepositoryDetailService inRepositoryDetailService;

    @Autowired
    private IPPurchaseService purchaseService;

    @Autowired
    private IPPurchaseDetailService purchaseDetailService;

    @Autowired
    private ICCheckService checkService;

    @Autowired
    private ICCheckDetailService checkDetailService;

    @Autowired
    private IWWearhouseService wearhouseService;

    @Autowired
    private IGoodsPartDetailService goodsPartDetailService;

    @Autowired
    private IGoodsPartService goodsPartService;

    @Autowired
    private IBybsService bybsService;

    @Autowired
    private IBybsDetailService bybsDetailService;

    @Autowired
    private InRepositoryDetailMapper inRepositoryDetailMapper;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISaleReturnService saleReturnService;

    @PostMapping
    @ResponseBody
    public MyResponseBody post(InRepositoryDetail inRepositoryDetail) {
        inRepositoryDetailService.insertOrUpdate(inRepositoryDetail);
        return MyResponseBody.success();
    }
    @GetMapping("list")
    @ResponseBody
    public Page list(InRepositoryDetailSearchDto searchDto, MyPage<InRepositoryDetail> page) {
        return inRepositoryDetailService.selectPage(searchDto, page);
    }

    @RequestMapping("getOne")
    @ResponseBody
    public List<Map> getOne(String code) {
        List<Map> maps = inRepositoryDetailService.getDetailByCode(code);
        for (Map dto : maps) {
            if ("0".equals(dto.get("type").toString())) {
                Wrapper wrapper = new EntityWrapper<>();
                wrapper.eq("id", dto.get("buszId"));
                PPurchaseDetail pPurchaseDetail = purchaseDetailService.selectOne(wrapper);
                dto.put("price", pPurchaseDetail.getAmountActual());
            }
            if ("6".equals(dto.get("type").toString())) {
                Wrapper wrapper = new EntityWrapper<>();
                wrapper.eq("id", dto.get("buszId"));
                SaleReturn saleReturn = saleReturnService.selectOne(wrapper);
                dto.put("price", saleReturn.getUnitPrice());
            }
        }
        List<Map> unit = sysDictService.selList(DictCodes.get("materiel_MU"));
        for (int i = 0;i < maps.size(); i++) {
            for (int j =0;j<unit.size();j++) {
                if (maps.get(i).get("unit") != null && maps.get(i).get("unit").toString().equals(unit.get(j).get("value"))) {
                    maps.get(i).put("unitName", unit.get(j).get("text"));
                }
            }
        }
         return maps;
    }

    @GetMapping
    public String index(Long houseId, ModelMap map) {
        if(houseId != null && houseId != 0) {
            map.put("houseId", houseId);
            WWearhouse house = this.wearhouseService.selectById(houseId);
            map.put("houseName", house.getName());

            //本月
            map.put("startTime", DateUtil.getMonthFirstDay(new Date()));
            map.put("endTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        }
        return "/inRepositoryDetail/inRepositoryDetail";
    }

    /**
     * 新增入库单页面跳转
     * */
    @RequestMapping("newAddInRepository")
    public String newAddInRepository(){
        return "/inRepositoryDetail/inRepositoryDetailAdd";
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        inRepositoryDetailService.delete(ids);
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(InRepositoryDetail inRepositoryDetail, ModelMap modelMap) {
        modelMap.put("id", inRepositoryDetail.getId());
        return "/inRepositoryDetail/inRepositoryDetail_edit";
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(inRepositoryDetailService.selectById(id));
        return responseBody;
    }

//    @PostMapping("add")
//    @ResponseBody
//    public MyResponseBody add(HttpServletRequest request){
//        String param = request.getParameter("param");
//        JSONObject jsonObject = JSON.parseObject(param);
//        //@SuppressWarnings("unchecked")
//        JSONArray list=jsonObject.getJSONArray("data");
//
//        MyResponseBody responseBody = MyResponseBody.success();
//        return responseBody;
//    }

    @PostMapping("add")
    @ResponseBody
    public MyResponseBody add(InRepositoryAddDTO dto, String goods) {
        MyResponseBody responseBody = MyResponseBody.success();
        List<InRepositoryGoodsDTO> goodsList = JSONArray.parseArray(goods, InRepositoryGoodsDTO.class);

        dto.setInRepositoryGoodsDTOs(goodsList);
        //
        inRepositoryDetailService.addInRepositoryDetail(dto);
        return responseBody;
    }
    @GetMapping("detail")
    public String detail(@RequestParam("code") String code, ModelMap modelMap) {
        modelMap.put("code", code);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("code", code);

        InRepositoryDetail detail = this.inRepositoryDetailService.selectOne(wrapper);
        modelMap.put("type", detail.getType());
        if(detail.getType() == 0) {//采购入库
            PPurchaseDetail purchaseDetail = this.purchaseDetailService.selectById(detail.getBuszId());
            PPurchase purchase = this.purchaseService.selectById(purchaseDetail.getPurchaseId());
            modelMap.put("ctime", DateUtil.DateToString(purchase.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            modelMap.put("username", purchase.getUsername());
            modelMap.put("orderTime", DateUtil.DateToString(purchase.getPtime(), DateStyle.YYYY_MM_DD));
        } else if(detail.getType() == 1) {//盘点入库
            CCheckDetail checkDetail = this.checkDetailService.selectById(detail.getBuszId());
            CCheck check = this.checkService.selectById(checkDetail.getCheckId());
            modelMap.put("ctime", DateUtil.DateToString(check.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            modelMap.put("username", check.getUsername());
            modelMap.put("orderTime", DateUtil.DateToString(check.getCtime(), DateStyle.YYYY_MM_DD));
        } else if(detail.getType() == 2) {//拆装入库
            GoodsPartDetail partDetail = this.goodsPartDetailService.selectById(detail.getBuszId());
            GoodsPart part = this.goodsPartService.selectById(partDetail.getPartId());
            modelMap.put("ctime", DateUtil.DateToString(part.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            modelMap.put("username", part.getCname());
            modelMap.put("orderTime", DateUtil.DateToString(part.getOrderTime(), DateStyle.YYYY_MM_DD));
        } else if(detail.getType() == 3) {//报溢入库
            BybsDetail bybsDetail = this.bybsDetailService.selectById(detail.getBuszId());
            Bybs bybs = this.bybsService.selectById(bybsDetail.getBybsId());
            modelMap.put("ctime", DateUtil.DateToString(bybs.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            modelMap.put("username", bybs.getCname());
            modelMap.put("orderTime", DateUtil.DateToString(bybs.getOrderTime(), DateStyle.YYYY_MM_DD));
        }

        return "/inRepositoryDetail/inRepositoryDetail_new";
    }

    @GetMapping("printDetail")
    public String printDetail(@RequestParam("code") String code, ModelMap modelMap) {
        modelMap.put("thisTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
        modelMap.put("code", code);
        String id = "(" + code +")";
        Map map = new HashMap<>();
        map.put("ids", id);
        List<Map> maps = inRepositoryDetailMapper.selectPrintList(map);
        Wrapper wrapper2 = new EntityWrapper<>();
        wrapper2.eq("code", maps.get(0).get("code"));
        List<InRepositoryDetail> inRepositoryDetails = inRepositoryDetailService.selectList(wrapper2);
        List idList = new ArrayList<>();
        for (InRepositoryDetail dto : inRepositoryDetails) {
            idList.add(dto.getWearhouseId());
        }
        String repositoryName = "";
        Wrapper wrapper1 = new EntityWrapper<>();
        wrapper1.in("id", idList);
        List<WWearhouse> wWearhouses = wearhouseService.selectList(wrapper1);
        for (WWearhouse nameDto : wWearhouses) {
            repositoryName += nameDto.getName() + "，";
        }
        repositoryName = repositoryName.substring(0,repositoryName.length() - 1);
        modelMap.put("repositoryName", repositoryName);
        modelMap.put("data", maps.get(0));
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("username", maps.get(0).get("username"));
        SysUser sysUser = sysUserService.selectOne(wrapper);
        if (sysUser != null) {
            modelMap.put("nickname", sysUser.getNickname());
        } else {
            modelMap.put("nickname", maps.get(0).get("username"));
        }


        List<Map> repository = sysDictService.selList(DictCodes.get("repository"));
        maps.get(0).put("orderTime",DateUtil.DateToString((Date) maps.get(0).get("orderTime"), DateStyle.YYYY_MM_DD));
        for (int j = 0; j < repository.size(); j++) {
            if (maps.get(0).get("type").toString().equals(repository.get(j).get("value"))) {
                maps.get(0).put("typeName", repository.get(j).get("text"));
            }
        }

        List<Map> goodsMap = inRepositoryDetailService.getDetailByCode((String) maps.get(0).get("code"));
        for (Map dto : goodsMap) {
            if ("0".equals(dto.get("type").toString())) {
                Wrapper wrapper3 = new EntityWrapper<>();
                wrapper3.eq("id", dto.get("buszId"));
                PPurchaseDetail pPurchaseDetail = purchaseDetailService.selectOne(wrapper3);
                BigDecimal price = pPurchaseDetail.getAmountActual().setScale(2);
                dto.put("price", price);
            }
        }
        Integer totalCount = 0;
        BigDecimal totalMoney = BigDecimal.ZERO;
        if (goodsMap != null && goodsMap.size() > 0) {
            for (int i = 0; i< goodsMap.size(); i++) {
                totalCount += (Integer) goodsMap.get(i).get("count");
                if (goodsMap.get(i).get("price") != null) {
                    BigDecimal count = new BigDecimal((Integer) goodsMap.get(i).get("count")) ;
                    BigDecimal price =  (BigDecimal) goodsMap.get(i).get("price") ;
                    BigDecimal multiply = count.multiply(price).setScale(2);
                    totalMoney = totalMoney.add(multiply);
                }
            }
        }
        modelMap.put("totalCount", totalCount);
        modelMap.put("totalMoney", totalMoney.toString());
        String capitalMoney = "零元整";
        if(BigDecimal.ZERO.compareTo(totalMoney)!=0){
            capitalMoney = MoneyTransformUtil.digitUppercase(totalMoney.toString());
        }
//        String capitalMoney = MoneyTransformUtil.digitUppercase(totalMoney.toString());
        modelMap.put("capitalMoney", capitalMoney);
        return "/inRepositoryDetail/printDetail";
    }

    @PostMapping("getBatchCodeIsExsit")
    @ResponseBody
    public MyResponseBody getBatchCodeIsExsit(String batchCode) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(inRepositoryDetailService.getBatchCodeIsExsit(batchCode));
        return responseBody;
    }

    @GetMapping("batchCodeGrid")
    public String batchCodeGrid(Long skuId, String batchCode, ModelMap modelMap) {
        modelMap.put("skuId", skuId);
        modelMap.put("batchCode", batchCode);
        return "/inRepositoryDetail/batchCodeGrid";
    }

    @PostMapping("batchCodeGrid")
    @ResponseBody
    public List<Map> batchCodeGrid(Long skuId) {
        return inRepositoryDetailService.batchCodeGrid(skuId);
    }

    @PostMapping("getDetailBySku")
    @ResponseBody
    public List<Map> getDetailBySku(Long houseId, Long goodsId, Long skuId) {
        return inRepositoryDetailService.getDetailBySku(houseId, goodsId, skuId);
    }

    /**
     * 根据出库数量，获取调整后的出库信息
     * @param skuId
     * @param num
     * @return
     */
    @PostMapping("getSkuHouseByNum")
    @ResponseBody
    public String getSkuHouseByNum(Long skuId, Integer num, Long houseId) {
        return inRepositoryDetailService.getSkuHouseByNum(skuId, num, houseId);
    }

    /**
     * 获取仓库下某规格的成本单价和库位
     * @param skuId
     * @param houseId
     * @return
     */
    @PostMapping("getSkuAvgCost2House")
    @ResponseBody
    public Map<String, Object> getSkuAvgCost2House(Long skuId, Long houseId) {
        Map<String, Object> map = new HashMap<>();
        map.put("avgCost", inRepositoryDetailService.getSkuAvgCostByHouseId(houseId, skuId));
        map.put("house", inRepositoryDetailService.getSkuHouseByHouseId(houseId, skuId));
        return map;
    }

    /**
     * 获取仓库下某规格：优先获取默认，若默认库位不在当前库位，则获取当前仓库下其他库位
     * @param materielId
     * @param houseId
     * @return
     */
    @PostMapping("getMaterielHouseByHouseId")
    @ResponseBody
    public Map<String, Object> getMaterielHouseByHouseId(Long materielId, Long houseId) {
        Map<String, Object> map = new HashMap<>();
        map.put("house", inRepositoryDetailService.getMaterielHouseByHouseId(houseId, materielId));
        return map;
    }

    @GetMapping("printList")
    public String printList(@RequestParam("ids") Long[] ids, ModelMap modelMap) {
        modelMap.put("thisTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
        String idsList = "(";
        for (int i = 0; i < ids.length; i++) {
            idsList += ids[i] + ",";
        }
        idsList = idsList.substring(0, idsList.length() - 1);
        idsList = idsList + ")";
        modelMap.put("ids",idsList);
        return "/inRepositoryDetail/inRepositoryList_print";
    }

    @RequestMapping("printData")
    @ResponseBody
    public List printData(@RequestParam("ids") String ids){
        Map map = new HashMap<>(2);
        map.put("ids", ids);
        List<Map> maps = inRepositoryDetailMapper.selectPrintList(map);
        List<Map> repository = sysDictService.selList(DictCodes.get("repository"));
        for (int i = 0;i < maps.size(); i++) {
            maps.get(i).put("orderTime",DateUtil.DateToString((Date) maps.get(i).get("orderTime"), DateStyle.YYYY_MM_DD));
            for (int j =0;j<repository.size();j++) {
                if (maps.get(i).get("type").toString().equals(repository.get(j).get("value"))) {
                    maps.get(i).put("typeName", repository.get(j).get("text"));
                }
            }
        }
        return maps;
    }
}
